<template>
  <div>
    <vxe-toolbar id="toolbarId" :setting="{ storage: true }" export :refresh="{ query: findList }">
      <template v-slot:buttons>
        <el-button @click="funcFilter">查询</el-button>
        <el-button v-if="!parentData.showInfo" @click="funcAdd">新增</el-button>
      </template>
    </vxe-toolbar>
    <vxe-table
      ref="xTable"
      border
      resizable
      stripe
      highlight-current-row
      highlight-hover-row
      row-id="id"
      height="700"
      :data="tableData"
      :loading="loading"
      remote-sort
      @sort-change="sortList"
    >
      <vxe-table-column>
        <vxe-table-column
          field="authStatus"
          title="审核状态"
          show-header-overflow
          show-overflow
          min-width="130"
          :formatter="formatterAuthStatus"
          sortable
        />
        <template v-slot:header>
          <el-select v-model="listQuery.authStatus" placeholder="请选择" clearable>
            <el-option
              v-for="item in authStatusOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </template>
      </vxe-table-column>
      <vxe-table-column>
        <vxe-table-column
          field="driverType"
          :formatter="formatterDriverType"
          title="司机类型"
          min-width="130"
          show-header-overflow
          show-overflow
          sortable
        />
        <template v-slot:header>
          <el-select v-model="listQuery.driverType" placeholder="请选择" clearable>
            <el-option
              v-for="item in driverTypeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </template>
      </vxe-table-column>
      <vxe-table-column>
        <vxe-table-column
          field="name"
          title="姓名"
          show-header-overflow
          min-width="130"
          show-overflow
          sortable
        />
        <template v-slot:header>
          <el-input v-model="listQuery.name" placeholder="请输入姓名" clearable />
        </template>
      </vxe-table-column>
      <vxe-table-column>
        <vxe-table-column
          field="phone"
          title="手机"
          show-header-overflow
          min-width="130"
          show-overflow
          sortable
        />
        <template v-slot:header>
          <el-input v-model="listQuery.phone" placeholder="请输入手机" clearable />
        </template>
      </vxe-table-column>
      <vxe-table-column>
        <vxe-table-column
          field="vehicleLicenseNumber"
          title="车牌号"
          show-header-overflow
          min-width="130"
          show-overflow
          sortable
        />
        <template v-slot:header>
          <el-input v-model="listQuery.vehicleLicenseNumber" placeholder="请输入车牌号" clearable />
        </template>
      </vxe-table-column>
      <vxe-table-column>
        <vxe-table-column
          field="identificationNumber"
          title="身份证号"
          show-header-overflow
          min-width="130"
          show-overflow
          sortable
        />
        <template v-slot:header>
          <el-input v-model="listQuery.identificationNumber" placeholder="请输入身份证号" clearable />
        </template>
      </vxe-table-column>
      <vxe-table-column>
        <vxe-table-column
          field="vehicleLoadWeightName"
          title="载重"
          show-header-overflow
          min-width="130"
          show-overflow
          sortable
        />
        <template v-slot:header>
          <el-select v-model="listQuery.vehicleLoadWeightCode" placeholder="请选择" clearable>
            <el-option
              v-for="item in parentData.vehicleTonnageList"
              :key="item.code"
              :label="item.name"
              :value="item.code"
            />
          </el-select>
        </template>
      </vxe-table-column>
      <vxe-table-column>
        <vxe-table-column
          field="driverLicenseDueDate"
          title="驾驶证到期"
          show-header-overflow
          min-width="420"
          show-overflow
          sortable
          :resizable="false"
        />
        <template v-slot:header>
          <el-date-picker
            v-model="driverLicenseDueDateRange"
            type="daterange"
            value-format="yyyy-MM-dd"
            :picker-options="pickerOptions"
            style="width:100%"
            range-separator="至"

            start-placeholder="开始日期"
            end-placeholder="结束日期"
            @change="value => changeDate(value, 'driverLicenseDueDate')"
          />
        </template>
      </vxe-table-column>
      <vxe-table-column>
        <vxe-table-column
          field="gmtCreated"
          title="注册时间"
          show-header-overflow
          show-overflow
          min-width="420px"
          sortable
          :resizable="false"
        />
        <template v-slot:header>
          <el-date-picker
            v-model="gmtCreatedRange"
            type="daterange"
            value-format="yyyy-MM-dd"
            :picker-options="pickerOptions"
            style="width:100%"
            range-separator="至"

            start-placeholder="开始日期"
            end-placeholder="结束日期"
            @change="value => changeDate(value, 'gmtCreated')"
          />
        </template>
      </vxe-table-column>
      <vxe-table-column v-if="!parentData.showInfo" title="操作" min-width="220" fixed="right">
        <template slot-scope="scope">
          <el-tooltip class="item" :hidden="scope.row.driverType === 0" effect="dark" content="编辑" placement="top">
            <vxe-button type="text" @click="funcEdit(scope.row.code)">
              <i class="el-icon-edit" />
            </vxe-button>
          </el-tooltip>
          <el-tooltip class="item" effect="dark" content="删除" placement="top">
            <vxe-button type="text" @click="funcDelete(scope.row.partyCode)">
              <i class="el-icon-delete" />
            </vxe-button>
          </el-tooltip>
          <template>
            <el-tooltip
              v-if="scope.row.isFreeze === 0"
              :hidden="scope.row.driverType === 0"
              class="item"
              effect="dark"
              content="冻结"
              placement="top"
            >
              <vxe-button type="text" @click="funcLock(scope.row)">
                <i class="el-icon-lock" />
              </vxe-button>
            </el-tooltip>
            <el-tooltip v-else :hidden="scope.row.driverType === 0" class="item" effect="dark" content="解冻" placement="top">
              <vxe-button type="text" @click="funcUnlock(scope.row)">
                <i class="el-icon-unlock" />
              </vxe-button>
            </el-tooltip>
          </template>
          <template>
            <el-tooltip
              v-if="scope.row.bindStatus === 1"
              :hidden="scope.row.driverType === 0"
              class="item"
              effect="dark"
              content="绑定车辆"
              placement="top"
            >
              <vxe-button type="text" @click="funcBind(scope.row)">
                <i class="el-icon-link" />
              </vxe-button>
            </el-tooltip>
            <el-tooltip v-else :hidden="scope.row.driverType === 0" class="item" effect="dark" content="解绑车辆" placement="top">
              <vxe-button type="text" @click="funcUnbind(scope.row)">
                <i class="el-icon-paperclip" />
              </vxe-button>
            </el-tooltip>
          </template>
        </template>
      </vxe-table-column>
    </vxe-table>
    <vxe-pager
      :loading="loading"
      :current-page.sync="listQuery.pageNum"
      :page-size.sync="listQuery.pageSize"
      :total="listQuery.total"
      :layouts="['PrevJump', 'PrevPage', 'Number', 'NextPage', 'NextJump', 'Sizes', 'FullJump', 'Total']"
      @page-change="handlePageChange"
    />

    <vxe-modal v-model="modelAddFlag" title="新增" width="800" height="600" resize>
      <compAdd
        :parent-data="parentData"
        @fatherAddMethod="fatherAdd"
        @fatherCancelMethod="fatherCancel"
      />
    </vxe-modal>
    <vxe-modal v-model="modelEditFlag" title="编辑" width="800" height="600" resize>
      <compEdit
        ref="editRef"
        :parent-data="parentData"
        @fatherEditMethod="fatherEdit"
        @fatherCancelMethod="fatherCancel"
      />
    </vxe-modal>
    <vxe-modal v-model="modelBindFlag" title="绑定车辆" width="600" height="400" resize>
      <compBind
        ref="bindRef"
        :parent-data="parentData"
        @fatherBindMethod="fatherBind"
        @fatherCancelMethod="fatherCancel"
      />
    </vxe-modal>
  </div>
</template>
<script>
import Vue from "vue";
import "xe-utils";
import VXETable from "vxe-table";
import "vxe-table/lib/index.css";
import XEUtils from "xe-utils";
import VXEUtils from "vxe-utils";
Vue.use(VXETable, VXEUtils, XEUtils, { mounts: ["cookie"] });
import compAdd from "./components/teamDirverAdd.vue";
import compEdit from "./components/teamDirverEdit.vue";
import compBind from "./components/teamDirverBind.vue";
import {
  getTeamDriverList,
  batchDelFromTeam,
  freezeTeamDriver,
  unfreezeTeamDriver,
  unbindVehicle
} from "@/api/driver";
export default {
  name: "TeamDriverList",
  components: {
    compAdd,
    compEdit,
    compBind
  },
  props: {
    parentData: {
      type: Object,
      default() {
        return {
          showInfo: false,
          areaOptions: [],
          vehicleBindList: [],
          vehicleTypeAllowList: [],
          vehicleClassificationList: [],
          vehicleLengthList: [],
          vehicleWidthList: [],
          vehicleHighList: [],
          vehicleTonnageList: [],
          locationSourceList: []
        };
      }
    }
  },
  data() {
    return {
      pickerOptions: {
        shortcuts: [
          {
            text: "最近一周",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", [start, end]);
            }
          },
          {
            text: "最近一个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit("pick", [start, end]);
            }
          },
          {
            text: "最近三个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit("pick", [start, end]);
            }
          }
        ]
      },
      loading: false,
      tableData: [],
      modelAddFlag: false,
      modelEditFlag: false,
      modelBindFlag: false,
      driverLicenseDueDateRange: "",
      gmtCreatedRange: "",
      listQuery: {
        teamCode: "",
        authStatus: "",
        name: "",
        phone: "",
        vehicleLicenseNumber: "",
        identificationNumber: "",
        vehicleLoadWeightCode: "",
        gmtCreatedStart: "",
        gmtCreatedEnd: "",
        pageNum: 1,
        pageSize: 10,
        sortField: "",
        sortType: "",
        total: 0
      },
      sumObject: {
        balance: 0
      },
      authStatusOptions: [
        { label: "未审核", value: 0, color: "gray" },
        { label: "审核中", value: 1, color: "#0000ff" },
        { label: "审核未通过", value: 2, color: "#ff0000" },
        { label: "审核通过", value: 3, color: "#00bd93" }
      ],
      // 司机/车队类型
      driverTypeOptions: [
        {
          label: "独立司机",
          value: 0
        },
        {
          label: "车队",
          value: 1
        },
        {
          label: "车队司机",
          value: 2
        }
      ]
    };
  },
  created() {
    this.listQuery.teamCode = this.$route.query.partyCode
      ? this.$route.query.partyCode
      : "";
    this.findList();
  },
  methods: {
    // 类型筛选
    formatterDriverType({ cellValue }) {
      let item = this.driverTypeOptions.find(item => item.value === cellValue);
      return item ? item.label : "";
    },
    findList() {
      this.loading = true;
      return new Promise(resolve => {
        getTeamDriverList(this.listQuery).then(response => {
          this.tableData = response.data.records;
          this.listQuery.total = response.data.total;
          this.sumObject = response.data.sumObject;
          this.loading = false;
          resolve();
        });
      })
    },
    // 查询
    funcFilter() {
      this.listQuery.pageNum = 1;
      this.findList();
    },
    // 排序
    sortList({ column, property, order }) {
      if (order) {
        this.listQuery.sortField = property;
        this.listQuery.sortType = order;
      } else {
        this.listQuery.sortField = "";
      }
      this.findList();
    },
    funcAdd() {
      this.modelAddFlag = true;
    },
    funcEdit(code) {
      this.$refs.editRef.getInfo(code);
      this.modelEditFlag = true;
    },
    funcDelete(codes) {
      this.$confirm("确认删除吗？")
        .then(_ => {
          batchDelFromTeam({ codes }).then(response => {
            this.$message({ message: response.msg, type: "success" });
            this.findList();
          });
        })
        .catch(_ => {});
    },
    funcLock(row) {
      this.$confirm("确认冻结吗？")
        .then(_ => {
          freezeTeamDriver({ partyCode: row.partyCode }).then(response => {
            this.$message({ message: response.msg, type: "success" });
            this.findList();
          });
        })
        .catch(_ => {});
    },
    funcUnlock(row) {
      this.$confirm("确认解冻吗？")
        .then(_ => {
          unfreezeTeamDriver({ partyCode: row.partyCode }).then(response => {
            this.$message({ message: response.msg, type: "success" });
            this.findList();
          });
        })
        .catch(_ => {});
    },
    funcBind(row) {
      this.$refs.bindRef.getInfo(row);
      this.modelBindFlag = true;
    },
    funcUnbind(row) {
      this.$confirm("确认解绑吗？")
        .then(_ => {
          unbindVehicle({
            vehicleCode: row.vehicleCode,
            partyCode: row.partyCode
          }).then(response => {
            this.$message({ message: response.msg, type: "success" });
            this.findList();
          });
        })
        .catch(_ => {});
    },
    fatherAdd() {
      this.modelAddFlag = false;
      this.findList();
    },
    fatherEdit() {
      this.modelEditFlag = false;
      this.findList();
    },
    fatherBind() {
      this.modelBindFlag = false;
      this.findList();
    },
    fatherCancel(modelFlag) {
      switch (modelFlag) {
        case "add":
          this.modelAddFlag = false;
          break;
        case "edit":
          this.modelEditFlag = false;
          break;
        case "bind":
          this.modelBindFlag = false;
          break;
      }
    },
    // 翻译审核状态
    formatterAuthStatus({ cellValue }) {
      const item = this.authStatusOptions.find(
        item => item.value === cellValue
      );
      return item ? item.label : "";
    },
    // 时间
    changeDate(value, prefix) {
      if (value) {
        this.listQuery[`${prefix}Start`] = value[0] + " 00:00:00";
        this.listQuery[`${prefix}End`] = value[1] + " 23:59:59";
      } else {
        this.listQuery[`${prefix}Start`] = "";
        this.listQuery[`${prefix}End`] = "";
      }
    },
    // 分页handle
    handlePageChange({ currentPage, pageSize }) {
      this.listQuery.pageNum = currentPage;
      this.listQuery.pageSize = pageSize;
      this.findList();
    }
  }
};
</script>

<style>
.vxe-table .vxe-body--column:not(.col--ellipsis),
.vxe-table .vxe-footer--column:not(.col--ellipsis),
.vxe-table .vxe-header--column:not(.col--ellipsis) {
  padding: 6px 0;
}
.vxe-toolbar {
  padding: 0 0 10px 0;
}
</style>
